package lsf.fund;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final TextView tv = new TextView(this);
        tv.setSingleLine(false);
        tv.setTextSize(48);
        setContentView(tv);

        for (final short i : new short[]{1051, 1227, 1208})
            new Thread() {
                @Override
                public void run() {
                    try {
                        JSONObject o = new JSONObject(get(url(i)).replaceAll("^.+?\\(|\\).*?$", ""));
                        final String s = o.getString("name").substring(0, 1) + ' ' + o.getString("gsz");
                        synchronized (MainActivity.this) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tv.append(s + '\n');
                                }
                            });
                        }
                    } catch (IOException | JSONException e) {
                        e.printStackTrace();
                    }
                }
            }.start();


    }

    private static String url(int code) {
        return "http://fundgz.1234567.com.cn/js/00" + code + ".js";
    }

    private static String get(String u) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(new URL(u).openStream()));

        StringBuilder sb = new StringBuilder();
        while (true) {
            String line = in.readLine();
            if (line != null)
                sb.append(line);
            else {
                in.close();
                return sb.toString();
            }
        }
    }
}